import { ref, reactive, computed } from "vue"

function useValidateForm(rule, rawFormData) {
	const report = ref([])
	const state = reactive({
		name: "",
		message: "",
		isError: false,
		isSuccess: false
	})
	const handle = (formData = rawFormData) => {
		report.value = []
		const reject = (name, message) => ({name, message})
		if(rule instanceof Function) {
			const result = rule(formData, reject)
			if(result) {
				report.value.push(result)
			}
		} else {
			rule.map(item => {
				const message = item.test(formData)
				if(message) {
					report.value.push(reject(item.name, message))
				}
			})
		}
		return report.value[0]
	}
	const validate = (formData = rawFormData) => {
		const result = handle(formData)
		if(result) {
			state.isError = true
			state.isSuccess = false
			state.name = result.name
			state.message = result.message
		} else{
			state.name = ""
			state.message = ""
			state.isError = false
			state.isSuccess = true
		}
		return result
	}
	const verify = (name) => {
		return computed(() => {
			const result = report.find(item => item.name === name)
			if(result) {
				return {
					isError: true,
					isSuccess: false,
					message: result.message
				}
			} else {
				return {
					isError: false,
					isSuccess: true,
				}
			}
		})
	}
	const reset = () => {
		report.value = []
		Object.assign(state.value, {
			name: "",
			message: "",
			isError: false,
			isSuccess: false
		})
	}
	const check = (name) => {
		if(rule instanceof Array) {
			const item = rule.find(item => item.name === name)
			if(item) {
				return item.test(rawFormData)
			}
			return true
		} else {
			return true
		}
	}
	return {
		state,
		reset,
		check,
		verify,
		validate
	}
}

export default useValidateForm